<template>
	<div class="content-box h100">
		<el-form class="drawer-multiColumn-form" label-width="100px">
			<div class="el-form-sub-title">导入门店</div>
			<div class="relative">
				<el-form-item label="文件上传 :">
					<el-upload
						ref="upload"
						class="upload"
						:auto-upload="false"
						:limit="parameter.excelLimit"
						:show-file-list="false"
						v-model:file-list="fileList"
						:before-upload="beforeExcelUpload"
						:on-exceed="handleExceed"
						:accept="parameter.fileType!.join(',')"
					>
						<el-button type="primary" link>选择文件</el-button>
						<template #tip>
							<slot name="tip">
								<div class="el-upload__tip">请上传 .xls , .xlsx 标准格式文件，文件最大为 {{ parameter.fileSize }}M</div>
							</slot>
						</template>
					</el-upload>
				</el-form-item>
				<el-button class="absolute top6" link style="left: 230px" type="primary" @click="downloadTemp"> 门店导入模板下载 </el-button>
			</div>
			<el-form-item label="文件名称 :">
				<div v-for="item in fileList" :key="item.url">
					{{ item.name }}
				</div>
			</el-form-item>
			<el-form-item type="submit">
				<el-button type="primary" @click="onImport">立即导入</el-button>
			</el-form-item>
			<div class="el-form-sub-title">导入记录</div>
			<ProTable ref="proTable" :columns="columns" :request-api="getTableList">
				<template #expand="scope">
					{{ scope.row }}
				</template>
			</ProTable>
		</el-form>
	</div>
</template>

<script setup lang="tsx" name="importStoreList">
import { ref } from 'vue';
import { useDownload } from '/@/hooks/useDownload';
import { ElNotification, UploadRequestOptions, UploadRawFile } from 'element-plus';
import ProTable from '../../../../components/ProTable/index.vue';

import { fetchStoreImport, fetchStoreDownload, fetchStoreImportRecord } from '/@/api/store';
import { downloadFile } from '/@/api/api';
import { genFileId } from 'element-plus';
import type { UploadInstance, UploadProps } from 'element-plus';
export interface ExcelParameterProps {
	title: string; // 标题
	fileSize?: number; // 上传文件的大小
	fileType?: any[]; // 上传文件的类型
	excelLimit?: number; // 上传文件的个数
	tempApi?: (params: any) => Promise<any>; // 下载模板的Api
	importApi?: (params: any) => Promise<any>; // 批量导入的Api
}

// 父组件传过来的参数
const parameter = ref<ExcelParameterProps>({
	title: '门店导入',
	excelLimit: 1,
	fileSize: 5,
	fileType: ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
	tempApi: fetchStoreDownload,
	importApi: fetchStoreImport,
});

const upload = ref<UploadInstance>();
const fileList = ref<any[]>([]);

// 接收父组件参数
const acceptParams = (params: ExcelParameterProps) => {
	parameter.value = { ...parameter.value, ...params };
};

// Excel 导入模板下载
const downloadTemp = () => {
	if (!parameter.value.tempApi) return;
	useDownload(fetchStoreDownload, `${parameter.value.title}模板`);
};

// 文件上传
const onImport = async () => {
	let excelFormData = new FormData();
	excelFormData.append('file', fileList.value[0].raw);
	await parameter.value.importApi!(excelFormData);
	proTable.value?.getTableList();
};

/**
 * @description 文件上传之前判断
 * @param file 上传的文件
 * */
const beforeExcelUpload = (file: UploadRawFile) => {
	const isExcel = parameter.value.fileType!.includes(file.type as File.ExcelMimeType);
	const fileSize = file.size / 1024 / 1024 < parameter.value.fileSize!;
	if (!isExcel)
		ElNotification({
			title: '温馨提示',
			message: '上传文件只能是 xls / xlsx 格式！',
			type: 'warning',
		});
	if (!fileSize)
		setTimeout(() => {
			ElNotification({
				title: '温馨提示',
				message: `上传文件大小不能超过 ${parameter.value.fileSize}MB！`,
				type: 'warning',
			});
		}, 0);
	return isExcel && fileSize;
};

// 文件数超出提示
const handleExceed: UploadProps['onExceed'] = (files) => {
	upload.value!.clearFiles();
	const file = files[0] as UploadRawFile;
	file.uid = genFileId();
	upload.value!.handleStart(file);
};

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	return fetchStoreImportRecord(params);
};

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'fileName',
		label: '文件名称',
	},
	{
		prop: 'count',
		label: '门店数量',
	},
	{
		prop: 'status',
		label: '处理状态',
		render: (scope: any) => {
			const color: any = {
				处理中: 'primary',
				处理成功: 'success',
				处理失败: 'danger',
			};
			return (
				<div>
					<el-text class="mx-1" type={color[scope.row.status]}>
						{scope.row.status}
					</el-text>

					{scope.row.status == '处理失败' && scope.row.errFileOssName && (
						<el-button type="primary" text onClick={() => onDownLoad(scope.row)}>
							{scope.row.errFileOssName}
						</el-button>
					)}
				</div>
			);
		},
	},
	{
		prop: 'completeTime',
		label: '完成时间',
	},
];

const onDownLoad = (row: string) => {
	useDownload(downloadFile, `门店导入_错误数据_${row.completeTime}`, { fileName: row.errFileOssName });
};

defineExpose({
	acceptParams,
});
</script>
<style lang="scss" scoped></style>
